import {TestCase, TestSuite, Tester} from '@rnoh/testerino';
import React, {useEffect, useState} from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Image,
  SafeAreaView,
  Button,
  ScrollView,
} from 'react-native';
import {getColors, cache} from 'react-native-image-colors';

export interface Config {
  fallback?: string;
  pixelSpacing?: number;
  quality?: 'lowest' | 'low' | 'high' | 'highest';
  headers?: Record<string, string>;
  cache?: boolean;
  key?: string;
}

const imgCat = require('../assets/cat.jpg');
const expo = require('../assets/expo.png');
const transparentImage = require('../assets/transparent.png');

const yunaUrl =
  'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024';
const base =
  '';

const title1 = `测试参数uri为 require('../assets/cat.jpg')`;
const httpTitle = `测试参数uri为 网络图片 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024'`;
const base64Title = `测试参数uri为 base64图片  '........'`;

export default function Demo() {
  const [colors, setColors] = useState({});
  const [colorsHttp, setColorsHttp] = useState({});
  const [colorsBase, setColorsBase] = useState({});

  const [colorsFallback, setColorsFallback] = useState({});
  const [colorsFallbackW, setColorsFallbackW] = useState({});

  const [colorsCache, setColorsCache] = useState({});
  const [colorsCacheW, setColorsCacheW] = useState({});

  const [colorsKey, setColorsKey] = useState({});
  const [colorsKeyW, setColorsKeyW] = useState({});

  const [colorsHeaders, setColorsHeaders] = useState({});
  const [colorsHeadersW, setColorsHeadersW] = useState({});

  const element = (colors: any) => {
    switch (colors.platform) {
      case 'android':
        return (
          <View style={{display: 'flex', flexDirection: 'row'}}>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.average,
              }}>
              <Text style={{color: 'white'}}>average</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.dominant,
              }}>
              <Text style={{color: 'white'}}>dominant</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.vibrant,
              }}>
              <Text style={{color: 'white'}}>vibrant</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.darkVibrant,
              }}>
              <Text style={{color: 'white'}}>darkVibrant</Text>
            </View>
          </View>
        );
      case 'ios':
        return (
          <View style={{display: 'flex', flexDirection: 'row'}}>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.primary,
              }}>
              <Text style={{color: 'white'}}>primary</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.background,
              }}>
              <Text style={{color: 'white'}}>background</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.secondary,
              }}>
              <Text style={{color: 'white'}}>secondary</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.detail,
              }}>
              <Text style={{color: 'white'}}>detail</Text>
            </View>
          </View>
        );
      case 'harmony':
        return (
          <View style={{display: 'flex', flexDirection: 'row'}}>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.mainColor,
              }}>
              <Text style={{color: 'white'}}>mainColor</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.largestProportionColor,
              }}>
              <Text style={{color: 'white'}}>largestProportionColor</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.highestSaturationColor,
              }}>
              <Text style={{color: 'white'}}>highestSaturationColor</Text>
            </View>
            <View
              style={{
                width: '25%',
                height: 80,
                backgroundColor: colors.averageColor,
              }}>
              <Text style={{color: 'white'}}>averageColor</Text>
            </View>
          </View>
        );
      default:
        return <View></View>;
    }
  };

  const fetchColors = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColors(result);
  };

  const fetchColorsHttp = async (uri: string) => {
    const result = await getColors(uri);
    setColorsHttp(result);
  };

  const fetchColorsBase = async (uri: string) => {
    const result = await getColors(uri);
    setColorsBase(result);
  };

  const fetchColorsFallback = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsFallback(result);
  };
  const fetchColorsFallbackW = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsFallbackW(result);
  };

  const fetchColorsCache = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsCache(result);
  };
  const fetchColorsCacheW = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsCacheW(result);
  };

  const fetchColorsKey = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsKey(result);
  };
  const fetchColorsKeyW = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsKeyW(result);
  };

  const fetchColorsHeaders = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsHeaders(result);
  };
  const fetchColorsHeadersW = async (uri: string, config?: Config) => {
    const result = await getColors(uri, config);
    setColorsHeadersW(result);
  };

  const [storage, setStorage] = useState('');
  const getCache = (key: string) => {
    setStorage(JSON.stringify(cache.getItem(key) || {}));
  };

  const [storageBase, setStorageBase] = useState('');
  const getCacheBase = (key: string) => {
    setStorageBase(JSON.stringify(cache.getItem(key) || {}));
  };

  const [storageHttp, setStorageHttp] = useState('');
  const getCacheHttp = (key: string) => {
    setStorageHttp(JSON.stringify(cache.getItem(key) || {}));
  };

  const [widgetsStorage, setWidgetsStorage] = useState('');
  const getWidgetsCache = (key: string) => {
    setWidgetsStorage(JSON.stringify(cache.getItem(key) || {}));
  };

  return (
    <ScrollView>
      <Tester>
        <TestSuite name="react-native-image-colors">
          <TestCase itShould={title1}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>{JSON.stringify(colors)}</Text>
                {element(colors)}
              </SafeAreaView>
              <Image
                resizeMode="contain"
                style={styles.image}
                source={imgCat}
              />
              <Button
                title={'uri为本地assets目录下的图片 拾取颜色'}
                onPress={() => {
                  fetchColors(imgCat);
                }}></Button>
            </View>
          </TestCase>

          <TestCase itShould={httpTitle}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>{JSON.stringify(colorsHttp)}</Text>
                {element(colorsHttp)}
              </SafeAreaView>
              <Image
                resizeMode="contain"
                style={styles.httpImage}
                source={{uri: yunaUrl}}
              />
              <Button
                title={'uri为网络图片 拾取颜色'}
                onPress={() => {
                  fetchColorsHttp(yunaUrl);
                }}></Button>
            </View>
          </TestCase>

          <TestCase itShould={base64Title}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>{JSON.stringify(colorsBase)}</Text>
                {element(colorsBase)}
              </SafeAreaView>
              <Image style={styles.httpImage} source={{uri: base}} />
              <Button
                title={'uri为base64格式的图片 拾取颜色'}
                onPress={() => {
                  fetchColorsBase(base);
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={
              '测试config参数 fallback为 #000000，该值只有当harmonyOS的api取到的颜色是空值时，返回值默认为fallback的值 #000000'
            }>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>
                  {JSON.stringify(colorsFallback)}
                </Text>
                {element(colorsFallback)}
              </SafeAreaView>
              <Image style={styles.httpImage} source={transparentImage} />
              <Button
                title={'测试config参数 fallback 拾取颜色'}
                onPress={() => {
                  fetchColorsFallback(transparentImage, {fallback: '#000000'});
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={
              '测试config参数 fallback为 #ffffff，该值只有当harmonyOS的api取到的颜色是空值时，返回值默认为fallback的值 #ffffff'
            }>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>
                  {JSON.stringify(colorsFallbackW)}
                </Text>
                {element(colorsFallbackW)}
              </SafeAreaView>
              <Image style={styles.httpImage} source={transparentImage} />
              <Button
                title={'测试config参数 fallback 拾取颜色'}
                onPress={() => {
                  fetchColorsFallbackW(transparentImage, {fallback: '#ffffff'});
                }}></Button>
            </View>
          </TestCase>
          
          <TestCase itShould={`测试config参数 headers为  "'a': 'a'"`}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>
                  {JSON.stringify(colorsHeaders)}
                </Text>
                {element(colorsHeaders)}
              </SafeAreaView>
              <Image
                resizeMode="contain"
                style={styles.httpImage}
                source={imgCat}
              />
              <Button
                title={`测试config参数 headers为 "'a': 'a'" 拾取颜色`}
                onPress={() => {
                  fetchColorsHeaders('http://10.51.126.22:5005/image', {
                    headers: {
                      a: 'a',
                    },
                  });
                }}></Button>
            </View>
          </TestCase>

          <TestCase itShould={`测试config参数headers为 "'a': 'A'"`}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>
                  {JSON.stringify(colorsHeadersW)}
                </Text>
                {element(colorsHeadersW)}
              </SafeAreaView>
              <Image
                resizeMode="contain"
                style={styles.httpImage}
                source={expo}
              />
              <Button
                title={'测试config参数 headers 拾取颜色'}
                onPress={() => {
                  fetchColorsHeadersW('http://10.51.126.22:5005/image', {
                    headers: {
                      a: 'A',
                    },
                  });
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={
              '测试config参数 cache为 true、 key为 localImage ，开启缓存时，key为localImage，缓存的值为该次调用getColors的返回值'
            }>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>{JSON.stringify(colorsKey)}</Text>
                {element(colorsKey)}
                <Text style={styles.loading}>
                  cache.getItem('localImage')的值
                </Text>
                <Text style={styles.result}>{storage}</Text>
              </SafeAreaView>
              <Image style={styles.image} source={imgCat} />
              <Button
                title={'测试config参数 cache key 拾取颜色'}
                onPress={async () => {
                  await fetchColorsKey(imgCat, {cache: true, key: 'localImage'});
                  getCache('localImage');
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={
              '测试config参数 cache为 false、 key为 baseImage ，不开启缓存时'
            }>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>Result:</Text>
                <Text style={styles.result}>{JSON.stringify(colorsKeyW)}</Text>
                {element(colorsKeyW)}
                <Text style={styles.loading}>
                  cache.getItem('baseImage')的值
                </Text>
                <Text style={styles.result}>{storageBase}</Text>
              </SafeAreaView>
              <Image style={styles.httpImage} source={{uri: base}} />
              <Button
                title={'测试config参数 cache key 拾取颜色'}
                onPress={async () => {
                  await fetchColorsKeyW(base, {cache: false, key: 'baseImage'});
                  getCacheBase('baseImage');
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={`测试cache.getItem()方法，读取缓存 调用方式cache.getItem('localImage');`}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>
                  cache.getItem('localImage')的值
                </Text>
                <Text style={styles.result}>{storage}</Text>
              </SafeAreaView>
              <Button
                title={`读取缓存 localImage`}
                onPress={() => {
                  getCache('localImage');
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={`测试cache.setItem()方法，设置缓存 调用方式cache.setItem('key', {a: 1, b: 2});`}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>cache.getItem('key')的值</Text>
                <Text style={styles.result}>{widgetsStorage}</Text>
              </SafeAreaView>
              <Button
                title={`设置缓存 key`}
                onPress={() => {
                  cache.setItem('key', {a: 1, b: 2});
                  getWidgetsCache('key');
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={`测试cache.removeItem()方法，删除缓存 调用方式cache.removeItem('localImage');`}>
            <View>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>
                  cache.getItem('localImage')的值
                </Text>
                <Text style={styles.result}>{storage}</Text>
              </SafeAreaView>
              <Button
                title={`删除缓存 localImage`}
                onPress={() => {
                  cache.removeItem('localImage');
                  getCache('localImage');
                }}></Button>
            </View>
          </TestCase>

          <TestCase
            itShould={`测试cache.clear()方法，清空缓存 调用方式cache.clear();`}>
            <View style={{marginBottom: 50}}>
              <SafeAreaView style={styles.resultContainer}>
                <Text style={styles.loading}>
                  cache.getItem: key && localImage 的值
                </Text>
                <Text style={styles.result}>
                  {storage}
                  {storageHttp}
                  {widgetsStorage}
                </Text>
              </SafeAreaView>
              <Button
                title={`清空缓存`}
                onPress={() => {
                  cache.clear();
                  getWidgetsCache('key');
                  getCache('localImage');
                }}></Button>
            </View>
          </TestCase>
        </TestSuite>
      </Tester>
    </ScrollView>
  );
}

interface BoxProps {
  value: string;
  name: string;
}

const Box = ({value, name}: BoxProps) => {
  return (
    <View
      style={[
        styles.box,
        {
          backgroundColor: value,
        },
      ]}>
      <Text style={styles.colorName}>{name}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  httpImage: {
    width: 200,
    height: 250,
  },
  image: {
    width: 144 * 1.5,
    height: 192 * 1.5,
  },
  colorName: {
    backgroundColor: 'white',
    padding: 4,
    fontSize: 18,
  },
  box: {
    flex: 1,
    backgroundColor: 'red',
    justifyContent: 'center',
    alignItems: 'center',
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    width: '100%',
  },
  resultContainer: {
    flex: 1,
    padding: 20,
    width: '100%',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loading: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  result: {
    textAlign: 'center',
    color: '#333333',
  },
});


export const displayName = "ImageColorsExample";
export const framework = "React";
export const category = "UI";
export const title = "react-native-image-colors";
export const documentationURL = "https://github.com/react-native-oh-library/react-native-image-colors";
export const description = "React Native Image Colors";

export const examples = [
    {
        title: "react-native-image-colors",
        render: function (): any {
            return <Demo />;
        },
    },
];
